package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Resource
    ApArticleMapper apArticleMapper;
    @Resource
    AdminFeign adminFeign;
    @Autowired
    StringRedisTemplate redisTemplate;


    //计算热文章
    @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        String date = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy--MM-dd 00:00:00"));
        List<ApArticle> apArticleList = apArticleMapper.selectArticleByDate(date);
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVoList = this.computeArticleScore(apArticleList);
        System.out.println("hotArticleVoList = " + hotArticleVoList);
        //3 为每一个频道缓存热点较高的30条文章
        this.cacheTagToRedis(hotArticleVoList);
    }

   /* @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
        //根据文章id查询文章数据
        ApArticle article = apArticleMapper.selectById(mess.getArticleId());
        if (article==null){
            log.info("未查询到相关文章id：{}",mess.getArticleId());
        }
        //更新文章 各个行为的值
        article.setComment(article.getComment()==null?0: (int) (article.getComment() + mess.getComment()));
        article.setLikes(article.getLikes()==null?0: (int) (article.getLikes() + mess.getLike()));
        article.setViews(article.getViews()==null?0: (int) (article.getViews() + mess.getView()));
        article.setCollection(article.getCollection()==null?0: (int) (article.getCollection() + mess.getCollect()));
        apArticleMapper.updateById(article);
        //计算文章的分
        Integer score = computeScore(article);

        //判断文章是否近日发布，*3
        String nowStr = DateUtils.dateToString(new Date());
        String publishStr = DateUtils.dateToString(article.getPublishTime());
        if (nowStr.equals(publishStr)){
            score=score*3;
        }
        //查询对应频道热点文章，替换分值较低的文章
        updateArticleCache(article,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+article.getChannelId());
        //查询推荐频道热点的文章，替换分值较低的文章
    }*/

   /* private void updateArticleCache(ApArticle article, Integer score, String cashkey) {
        ValueOperations<String, String> valueOper = redisTemplate.opsForValue();
        String articleVoListJson = valueOper.get(cashkey);
        if (StringUtils.isNotBlank(articleVoListJson)){
            boolean isHas=false;
            //判断当前文章是否存在热点文章中
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleVoListJson, HotArticleVo.class);
            for (HotArticleVo articleVo : hotArticleVoList) {
                if (articleVo.getId().equals(article.getId())){
                    articleVo.setScore(score);
                    isHas=true;
                    break;
                }
            }
            if (!isHas){
                HotArticleVo articleVo = new HotArticleVo();
                BeanUtils.copyProperties(article,articleVo);
                articleVo.setScore(score);
                hotArticleVoList.add(articleVo);
            }

             hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30)
                    .collect(Collectors.toList());
            //缓存到redis中
            valueOper.set(cashkey,JSON.toJSONString(hotArticleVoList));
        }
    }*/

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        if (responseResult.checkCode()){
            List<AdChannel> list = responseResult.getData();
            //遍历当前列表，筛选出当前频道下的文章
            for (AdChannel adChannel : list) {
                //每个频道下的文章进行缓存
                List<HotArticleVo> articleVos = hotArticleVoList.stream().filter(hotArticle ->
                        hotArticle.getChannelId().equals(adChannel.getId())
                ).collect(Collectors.toList());
                this.sortAndCache(articleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+adChannel.getId());
            }
        }
        //给推荐频道缓存30条数据，所有文章排序之后的前30条
        sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存热点文章
     * @param articleVos
     * @param
     */
    private void sortAndCache(List<HotArticleVo> articleVos, String cachKey) {
        //对文章进行排序
        List<HotArticleVo> collect = articleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30).collect(Collectors.toList());
        redisTemplate.opsForValue().set(cachKey, JSON.toJSONString(collect));
    }

    /**
     * 计算热点文章的分值
     *
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
        List<HotArticleVo> collect = apArticleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            // 2.1计算文章分值算法
            Integer score = this.computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 计算分值算法
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * 3;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * 5;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * 8;
        }
        return score;
    }






    /**
     * 重新计算文章分值
     * @param mess
     */
    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
        //1 查询文章
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2 修改文章的行为数据（阅读1、点赞3、评论5、收藏8）
        if (mess.getView() != 0) {
            int view = (int) (apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
            apArticle.setViews(view);
        }
        if (mess.getLike() != 0) {
            int like = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
            apArticle.setLikes(like);
        }
        if (mess.getComment() != 0) {
            int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
            apArticle.setComment(comment);
        }
        if (mess.getCollect() != 0) {
            int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
            apArticle.setCollection(collection);
        }
        apArticleMapper.updateById(apArticle);
        //3 计算文章分值
        Integer score = computeScore(apArticle);
        // 如果是今天发布的文章，热度*3
        String publishStr = DateUtils.dateToString(apArticle.getPublishTime());
        String nowStr = DateUtils.dateToString(new Date());
        if (publishStr.equals(nowStr)){
            score = score*3;  //当天热点数据 *3
        }
        //4 更新缓存（频道）
        updateArticleCache(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //5 更新推荐列表的缓存
        updateArticleCache(apArticle, score,  ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ ArticleConstants.DEFAULT_TAG);
    }
    /**
     * 更新文章缓存
     * @param apArticle  当前文章
     * @param score 分数
     * @param cacheKey
     */
    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        boolean flag = false;
        String hotArticleListJson = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(hotArticleListJson)) {
            List<HotArticleVo> hotArticleList = JSONArray.parseArray(hotArticleListJson,HotArticleVo.class);
            //1 如果当前缓存中有当前文章，更新分值
            for (HotArticleVo hotArticleVo : hotArticleList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = true;
                    break;
                }
            }
            //2 缓存中没有当前文章
            if (!flag) {
                HotArticleVo hotArticle = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticle);
                hotArticle.setScore(score);
                hotArticleList.add(hotArticle);
            }
            //3. 将热点文章集合 按得分降序排序  取前30条缓存至redis中
            hotArticleList = hotArticleList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleList));
        }
    }
}
